package beans;

import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;

public class MusicPlayer
{		

	public String AudioFilePath;//目标音频文件路径

	public int state;//1.尚未开始 2.播放中

	public MusicPlayer(String AudioFilePath)
	{
		this.AudioFilePath=AudioFilePath;
		state = 1;
	}
	public void startPlayer()//开始播放
	{
		if(state != 1) return;
		state =2;
		new Thread(new Runnable()
		{
			public void run()
			{
				try
				{
					File file = new File(AudioFilePath);
					AudioInputStream stream = AudioSystem
							.getAudioInputStream(file);
					AudioFormat format = stream.getFormat();
					DataLine.Info info = new DataLine.Info(
							SourceDataLine.class, format);
					SourceDataLine line = (SourceDataLine) AudioSystem
							.getLine(info);
					byte[] buf = new byte[512 * 1024];
					line.open();
					line.start();
					int nbytes = 0;
					while (nbytes != -1)
					{
						if( state==3)  
							break;
						
						nbytes = stream.read(buf, 0, buf.length);
						
						if (nbytes >= 0)
							line.write(buf, 0, nbytes);
					}
					line.drain();
					line.close();
				}
				catch (UnsupportedAudioFileException e)
				{
					e.printStackTrace();
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}
				catch (LineUnavailableException e)
				{
					e.printStackTrace();
				}
			}
		}).start();
	}
	
	public void stopPlayer()//停止播放
	{
		state = 3;
	}
}
